<template>
    <div>
        <!-- 顶部导航栏 -->
        <div class="top">
            <div class="biaoti">考试系统</div>
            <div>
                <button @click="goToLogin">登录</button>
                <button @click="goToRegister">注册</button>
            </div>
        </div>
        <div class="login-wrap">
            <div class="image-container">
                <img src="../assets/img/login.jpg" alt="Login Image" class="login-image" />
            </div>
            <el-form :label-position="labelPosition" label-width="auto" :model="formLabelAlign" class="login-container"
                :rules="rules" ref="ruleFormRef">
                <div class="register-title">用户注册</div>
                <el-form-item label=" 学生学号" prop="studentId">
                    <el-input v-model="formLabelAlign.studentId" placeholder="请输入学生学号" clearable />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="formLabelAlign.name" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="formLabelAlign.gender">
                        <el-radio label="male">男</el-radio>
                        <el-radio label="female">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="班级" prop="class">
                    <el-input v-model="formLabelAlign.class" placeholder="请输入班级" clearable />
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input v-model="formLabelAlign.password" type="password" placeholder="请输入密码" show-password
                        clearable />
                </el-form-item>
                <el-form-item label="确认密码" prop="reType">
                    <el-input v-model="formLabelAlign.reType" type="password" placeholder="请再次输入密码" show-password
                        clearable />
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                    <div class="code-container">
                        <el-input v-model="formLabelAlign.code" placeholder="请输入验证码" clearable style="width: 65%;" />
                        <Captcha v-model:code="randomCode" class="code-img" />
                    </div>
                </el-form-item>
                <!-- 按钮提交组 -->
                <el-form-item class="btn-box">
                    <el-button type="primary" native-type="reset" style="width: 40%;">重置</el-button>
                    <el-button type="success" style="width: 40%;" native-type="submit"
                        @click.prevent="submitForm">注册</el-button>
                </el-form-item>
                <!-- 已有账号，去登录按钮 -->
                <el-form-item class="tologin">
                    <router-link class="link-div" to="/">已有账号？去登录</router-link>
                </el-form-item>
            </el-form>
        </div>
        <!-- 底部信息 -->
        <div class="footer">
            帮助中心  |  服务支持  |  售后服务  |  服务网点  |  线下门店  |  申请商家  |  加入我们  |  关于我们  |  友情链接
            <p>©福福传媒出品</p>
        </div>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { reactive, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUser } from '@/stores/userInfo';
import Captcha from '../components/Captcha.vue';

const userStore = useUser()
const router = useRouter()
const labelPosition = ref('right')
const remember = ref(false)
const ruleFormRef = ref()
const formLabelAlign = reactive({
    studentId: '',
    name: '',
    gender: 'male',
    class: '',
    password: '',
    code: '',
    reType: '',
})

// 随机验证码
const randomCode = ref('');

// 生成随机验证码
const generateRandomCode = () => {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let code = '';
    for (let i = 0; i < 4; i++) {
        code += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return code;
};

onMounted(() => {
    randomCode.value = generateRandomCode();
});

// 定义验证规则
const rules = reactive({
    studentId: [{
        required: true,
        message: '请输入学生学号',
        trigger: 'blur'
    },],
    name: [{
        required: true,
        message: '请输入姓名',
        trigger: 'blur'
    },],
    gender: [{
        required: true,
        message: '请选择性别',
        trigger: 'change'
    },],
    class: [{
        required: true,
        message: '请输入班级',
        trigger: 'blur'
    },],
    password: [{
        required: true,
        message: '请输入密码',
        trigger: 'blur'
    },],
    reType: [{
        required: true,
        message: '请输入确认密码',
        trigger: 'blur'
    },],
    code: [{
        required: true,
        message: '请输入验证码',
        trigger: 'blur'
    },],
})

const submitForm = () => {
    ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
            if (formLabelAlign.password !== formLabelAlign.reType) {
                ElMessage.error("两次密码输入不一致")
                return false;
            }
            if (formLabelAlign.code.toLowerCase() !== randomCode.value.toLowerCase()) {
                ElMessage.error("验证码错误")
                return false;
            }
            // 保存完整的用户信息
            const data = {
                username: formLabelAlign.studentId, // 将 studentId 作为 username 保存
                studentId: formLabelAlign.studentId,
                name: formLabelAlign.name,
                gender: formLabelAlign.gender,
                class: formLabelAlign.class,
                password: formLabelAlign.password
            };
            userStore.SET_USER_INFO(data)
            console.log(userStore.userInfo);
            ElMessage.success(`用户${formLabelAlign.studentId},注册成功！`)
            router.push('/login')
        } else {
            ElMessage.error('验证失败')
        }
    })
}
// 记住密码的状态
const rememberStatus = (status) => {
    console.log(status);
    remember.value = status
    if (status) {
        // 如果为true保存数据
        sessionStorage.setItem('formLabelAlign', JSON.stringify({
            ...formLabelAlign,
            status: remember.value
        }))
    } else {
        // 如果为false就清空数据
        sessionStorage.clear()
    }
}

// 跳转到登录页面
const goToLogin = () => {
    router.push('/login');
}
// 跳转到注册页面
const goToRegister = () => {
    router.push('/register');
}
</script>

<style scoped>
.top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
}

.biaoti {
    margin-left: 20px;
    font-size: 20px;
}

.top button {
    border: 2px solid #03BB7A;
    padding: 8px 16px;
    cursor: pointer;
    margin-left: 10px;
    border-radius: 8px; /* 添加圆角边框 */
}

.top button:nth-of-type(1) {
    background-color: white;
    color: #03BB7A;
}

.top button:nth-of-type(2) {
    background-color: #03BB7A;
    color: white;
}

.login-wrap {
    box-sizing: border-box;
    width: 100vw;
    height: 80vh;
    background-color: #EEEEEE;
    display: flex;
    justify-content: center;
    align-items: center;
}

.image-container {
    margin-right: 100px;
    /* 图片与表单之间的间距 */
}

.login-image {
    width: 500px;
    /* 根据需要调整图片大小 */
    height: auto;
}

.login-container {
    width: 300px;
    padding: 35px;
    background-color: white;
    border-radius: 6px;
    box-shadow: 0 0 20px 0 #ffff;
}

.register-title {
    text-align: center;
    margin-bottom: 15px;
    font-size: 18px;
    font-weight: bold;
    color: #03BB7A;
}

.el-input {
    height: 38px;
}

.code-container {
    display: flex;
    align-items: center;
    gap: 8px;
}

.code-img {
    flex-shrink: 0;
}

.link-div {
    color: red;
    text-decoration: none;
    font-family: sans-serif;
    font-size: 10px;
}

::v-deep(.btn-box>.el-form-item__content) {
    display: flex;
    justify-content: space-between;
}

::v-deep(.tologin>.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
}

/* 底部样式 */
.footer {
    background-color: black;
    color: white;
    text-align: center;
    padding: 10px;
}
</style>